import { InputNumberC, ModalC, TableC } from '@/comps/index';
import PropTypes from 'prop-types';
import React, { useState, useEffect } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { cloneDeep } from 'lodash';
import { divide, times } from 'number-precision';
import { connect } from 'dva';
import { namespace } from '@/src/newModels/leverageAnalysis/PortfolioManageLeverageAnalysisM';
import { InfoCircleOutlined } from '@ant-design/icons';
import { useLocalStorageState } from 'ahooks';
import { message } from 'antd';

const LabelSettingModal = (props) => {
  const { visible = false, operate, form, dispatch, loading } = props;
  const [userName, setUserName] = useState(undefined);
  const [isAdmin, setIsAdmin] = useState(false);
  const [dataSource, setDataSource] = useState([
    {
      productType: '1',
      highCriticalValue: 110,
      lowCriticalValue: 100,
      middleCriticalValue: 105,
    },
    {
      productType: '2',
      highCriticalValue: 120,
      lowCriticalValue: 100,
      middleCriticalValue: 110,
    },
    {
      productType: '3',
      highCriticalValue: 120,
      lowCriticalValue: 100,
      middleCriticalValue: 110,
    },
  ]);
  const getLabelSetData = () => {
    dispatch({
      type: `${namespace}/queryLabelSetData`,
      payload: {},
      callback: (data) => {
        if (data) {
          const dataCopy = cloneDeep(data?.dataSource);
          const res = dataCopy.map((ele) => ({
            ...ele,
            highCriticalValue: times(ele.highCriticalValue, 100),
            lowCriticalValue: times(ele.lowCriticalValue, 100),
            middleCriticalValue: times(ele.middleCriticalValue, 100),
          }));
          setUserName(data.userName);
          setIsAdmin(data.isConsistent);
          data?.dataSource?.length !== 0 && setDataSource(res);
        }
      },
    });
  };
  useEffect(() => {
    getLabelSetData();
  }, []);
  /**
   * 修改值
   * @param {number} e 修改后的值
   * @param {object} record 行数据
   * @param {string} key rowKey
   */
  const changeCriticalValue = (e, record, key) => {
    const dataSourceCopy = cloneDeep(dataSource);
    dataSourceCopy.map((ele) => {
      if (record.productType === ele.productType) {
        ele[key] = e;
      }
    });
    setDataSource(dataSourceCopy);
  };
  const onOkLabelSet = () => {
    const payloadData = cloneDeep(dataSource);
    payloadData.map((v) => {
      // ['highCriticalValue', 'lowCriticalValue', 'middleCriticalValue']
      v.highCriticalValue = divide(v.highCriticalValue ?? 0, 100);
      v.lowCriticalValue = divide(v.lowCriticalValue ?? 0, 100);
      v.middleCriticalValue = divide(v.middleCriticalValue ?? 0, 100);
    });
    const isSatisfy = ({ highCriticalValue, middleCriticalValue, lowCriticalValue }) => {
      return highCriticalValue > middleCriticalValue && highCriticalValue > lowCriticalValue && middleCriticalValue > lowCriticalValue;
    };
    const productType1Obj = dataSource.find((v) => v.productType == '1');
    const productType2Obj = dataSource.find((v) => v.productType == '2');
    const productType3Obj = dataSource.find((v) => v.productType == '3');

    if (!isSatisfy(productType1Obj)) return message.warning('现金管理类必须满足：高临界值>中临界值>低临界值!');
    if (!isSatisfy(productType2Obj)) return message.warning('开放式公募必须满足：高临界值>中临界值>低临界值!');
    if (!isSatisfy(productType3Obj)) return message.warning('封闭式及其他必须满足：高临界值>中临界值>低临界值!');
    dispatch({
      type: `${namespace}/saveLabelSet`,
      payload: {
        dataSource: payloadData,
      },
      callback: (success) => {
        if (success) operate(false);
      },
    });
  };
  const columns = [
    {
      key: 'productType',
      title: '产品形态',
      render: (_) => {
        return _ == 1 ? '现金管理类' : _ == 2 ? '开放式公募' : _ == 3 ? '封闭式及其他' : '--';
      },
    },
    {
      key: 'highCriticalValue',
      title: '高临界值设置(%)',
      align: 'right',
      render: (text, record) => {
        return (
          <InputNumberC
            disabled={!isAdmin}
            form={form}
            dataIndex={`highCriticalValue${record.productType}`}
            splitStyle={true}
            precision={2}
            initialValue={record.highCriticalValue}
            onChange={(e) => changeCriticalValue(e, record, 'highCriticalValue')}
          />
        );
      },
    },
    {
      key: 'middleCriticalValue',
      title: '中临界值设置(%)',
      align: 'right',
      render: (text, record) => {
        return (
          <InputNumberC
            disabled={!isAdmin}
            form={form}
            dataIndex={`middleCriticalValue${record.productType}`}
            splitStyle={true}
            precision={2}
            initialValue={record.middleCriticalValue}
            onChange={(e) => changeCriticalValue(e, record, 'middleCriticalValue')}
          />
        );
      },
    },
    {
      key: 'lowCriticalValue',
      title: '低临界值设置(%)',
      align: 'right',
      render: (text, record) => {
        return (
          <InputNumberC
            disabled={!isAdmin}
            form={form}
            dataIndex={`lowCriticalValue${record.productType}`}
            splitStyle={true}
            precision={2}
            initialValue={record.lowCriticalValue}
            onChange={(e) => changeCriticalValue(e, record, 'lowCriticalValue')}
          />
        );
      },
    },
  ];
  return (
    <div>
      <ModalC
        title={'标签设置'}
        visible={visible}
        maskClosable={false}
        onOk={onOkLabelSet}
        onCancel={() => {
          operate(false);
        }}
        width={900}
        footer={isAdmin ? undefined : null}
      >
        <TableC hidePage={true} columns={columns} dataSource={dataSource || []} rowKey='productType' size='small' loading={loading.effects[`${namespace}/queryLabelSetData`]} />
        <div style={{ width: '100%', height: 76, background: 'rgba(35,102,255,0.05)', paddingLeft: 13 }}>
          <div style={{ color: '#4376FF', fontSize: '14px', height: '44px', lineHeight: '44px' }}>
            <InfoCircleOutlined style={{ color: '#4376FF', marginRight: 5 }} />
            <span>标签按区间内平均杠杆率计算。</span>
          </div>
          <div style={{ color: '#4376FF', fontSize: '14px' }}>
            <InfoCircleOutlined style={{ color: '#4376FF', marginRight: 5 }} />
            <span>您所在机构的管理员是{userName}，如需调整设置请联系管理员。</span>
          </div>
        </div>
      </ModalC>
    </div>
  );
};
LabelSettingModal.propsTypes = {
  visible: PropTypes.bool.isRequired, // 是否显示
  operate: PropTypes.func.isRequired, // 按钮操作函数,true确定,false取消
};
const LabelSettingModalWithForm = Form.create()(LabelSettingModal);
const mapState = ({ loading, globalM }) => ({ loading, globalM });
export default connect(mapState)(LabelSettingModalWithForm);
